package FileHandling;

import java.io.*;
import javax.microedition.io.*;
import Map.Constants;
import Map.Mindmap;
import Map.Node;
import javax.microedition.rms.RecordStoreException;

/**
 * Hanles file, server and RMS operations of mindmaps
 *
 * @author Lewis Marhin and John Gray-Spence
 */
public class FileOps {

    private static Node[] nodeL;
    private static String fileN;
    private static Mindmap mindM;

    /** 
     * Saves a file to local memory with specified filename. Overwrites existing.
     *
     * @param n The list of nodes (i.e. the mindmap) to be written to file.
     * @param fn The filename to be used.
     */
    public static void saveFile(Node[] n, String fn) {
        // Based on http://www.java-tips.org/java-me-tips/midp/how-to-write-to-a-file.html
        nodeL = n;
        fileN = fn;

        new Thread() {

            public void run() {
                try {
                    OutputConnection toFile = (OutputConnection) Connector.open("file://c:/mindmaps/" + fileN + ".mm;append=false", Connector.WRITE);
                    PrintStream out = new PrintStream(toFile.openOutputStream());
                    out.print("<map version=\"" + Constants.VERSION + "\">");
                    for (int i = 0; i < nodeL.length; i++) {
                        if (nodeL[i] != null) {
                            out.print("<nodeID=\"" + Integer.toString(i) +
                                    "\" TEXT=\"" + nodeL[i].getDesc() +
                                    "\" PARENT=" + nodeL[i].getParent() +
                                    "\" X_POS=\"" + nodeL[i].getXloc() +
                                    "\" Y_POS=\"" + nodeL[i].getYloc() +
                                    "\">");
                        }
                    }
                    out.print("</node></map>");
                    out.print("\n");
                    out.close();
                    toFile.close();
                } catch (IOException e) {
                    // ERROR SAVING MIND MAP
                } catch (Exception e) {
                    // ERROR
                }
            }
        }.start();
    }

    /** 
     * Sends a file to a server running on a local machine.
     *
     * @param n The list of nodes (i.e. the mindmap) to be sent.
     * @param fn The filename to be used.
     */
    public static void saveFileServer(Map.Node[] n, String fn) {
        // Based off http://www.java2s.com/Code/Java/J2ME/Socketconnection.htm
        nodeL = n;
        fileN = fn;

        new Thread() {

            public void run() {
                try {
                    StreamConnection connection = (StreamConnection) Connector.open("socket://127.0.0.1:1337");
                    PrintStream out = new PrintStream(connection.openOutputStream());

                    out.print("SendingRatedMaps");
                    out.print("\n");
                    out.print("1");
                    out.print("\n");
                    out.print("rating");
                    out.print("\n");
                    out.print("catagory");
                    out.print("\n");
                    String tmp = "";
                    out.print("<map version=\"" + Constants.VERSION + "\">");
                    for (int i = 0; i < nodeL.length; i++) {
                        if (nodeL[i] != null) {
                            tmp += "<node ID=\"" + Integer.toString(i) +
                                    "\" TEXT=\"" + nodeL[i].getDesc() +
                                    "\" PARENT=" + nodeL[i].getParent() +
                                    "\" X_POS=\"" + nodeL[i].getXloc() +
                                    "\" Y_POS=\"" + nodeL[i].getYloc() +
                                    "\">";
                        }
                    }
                    out.print(tmp);
                    out.print("</node></map>");
                    out.print("\n");
                    out.print(fileN);
                    out.print("\n");

                    connection.close();
                } catch (IOException e) {
                    // do tnothing for now
                } catch (Exception e) {
                    // do nothing for now
                }
            }
        }.start();
    }

    /** 
     * Loads a mindmap from local memory.
     *
     * @param fn The name of the file to be loaded.
     * @return A list of Node objects suitable for a mindmap.
     */
    public static Node[] loadFile(String fn) {
        // laod file
        return null;
    }

    /** 
     * Saves a Mindmap object to Record Management System.
     *
     * @param m
     */
    public static void saveRMS(Mindmap m) {
        mindM = m;

        new Thread() {

            public void run() {
                try {
                    LocalStorage.addMap(mindM);
                } catch (RecordStoreException ex) {
                    ex.printStackTrace();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * Loads a Mindmap object from the Record Management System.
     *
     * @return A minmap object that can replace the default/current map.
     */
    public static Mindmap loadRMS() {

        new Thread() {

            public void run() {
                try {
                    mindM = LocalStorage.readMap();
                } catch (RecordStoreException ex) {
                    ex.printStackTrace();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }.start();

        return mindM;
    }
}
